import time
import csv
import json
import re
from os import system

from playwright.sync_api import sync_playwright


def handle_json(json):
    csvFile = open("./data/storeD_20230201.csv", 'a', encoding='utf-8', newline='')
    try:
        writer = csv.writer(csvFile)
        results = json['data']['list']
        # print(results)
        for i in range(0, len(results)):
            data_list = json['data']['list'][i]
            # print(data_list)
            # print(data_list['f0'])
            # print(data_list['f1'])
            # print(data_list['f2'])
            writer.writerow((data_list['f0'], data_list['f1'], data_list['f2']))
    finally:
        csvFile.close()


def on_response(response):
    # print(response)
    if '/datasearch/data/nmpadata/search' in response.url and response.status == 200:
        handle_json(response.json())


def run():
    with sync_playwright() as p:
        for browser_type in [p.firefox]:
            # 列表末尾加百度防止监听报错
            browser = browser_type.launch(headless=False)
            # page = browser.new_page()
            context = browser.new_context()
            page = context.new_page()
            # page.on('response', on_response)
            page.goto('https://www.nmpa.gov.cn/datasearch/search-result.html')
            # time.sleep(10)
            page.locator("text=关闭").click()

            # Click [placeholder="请选择"]
            page.locator("[placeholder=\"请选择\"]").click()

            # Click text=药品经营企业 >> nth=0
            page.fill('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/input', '苏DA')
            page.locator("text=药品经营企业").first.click()
            # time.sleep(2)
            page.wait_for_timeout(2000)
            page.click('//*[@id="home"]/main/div[1]/div[7]/div/div[2]/div/button')
            # time.sleep(2)
            # page.wait_for_timeout(2000)
            with context.expect_page() as new_page_info:
                register_page = new_page_info.value
                #  cancel_request(route, request):
                #    route.abort()
                # register_page.route(re.compile(r"(\.png)|(\.jpg)"), cancel_request)
                register_page.wait_for_load_state()
                # print(register_page.title())
                register_page.wait_for_timeout(5000)
                register_page.locator("text=关闭").click()
                register_page.on('response', on_response)
                register_page.wait_for_timeout(2000)
                # 设置每页展示条数
                register_page.click('//*[@id="home"]/div[3]/div[3]/div/div/span[2]/div/div/input')
                register_page.locator("text=20条/页").first.click()

                # region 定位遍历的坐标
                hello = open("./data/storeD.csv", 'r', encoding='utf-8')
                # con = hello.readline()
                strLine = hello.readline().split(',')
                print(strLine)
                con = strLine[0]
                countStr = int(strLine[1])
                print(con)
                hello.close()
                # 终止检测任务
                if con == 'end':
                    system('taskkill /F /IM cmd.exe')
                list = storeList[storeList.index(con) + 0:]

                # endregion 定位遍历的坐标
                print(list)
                print(storeList)
                # 输入筛选条件
                for item in list:
                    # 终止检测任务
                    if item == 'end':
                        system('taskkill /F /IM cmd.exe')

                    register_page.fill('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/input', item)
                    register_page.click('//*[@id="home"]/div[3]/div[1]/div[1]/div[2]/div/div/button')
                    # time.sleep(5)
                    # pageStr = register_page.query_selector('span.el-pagination__total').text_content()
                    # pageCount = int(pageStr.split(' ', 2)[1])
                    # print(pageCount)
                    count = countStr

                    # region 跳转到指定页码
                    register_page.wait_for_timeout(3000)
                    register_page.fill('//*[@id="home"]/div[3]/div[3]/div/div/span[3]/div/input', str(count))
                    register_page.keyboard.press("Enter")
                    register_page.wait_for_timeout(1000)
                    # endregion 跳转到指定页码

                    while True:
                        # region 记录当前节点及页码
                        with open("./data/storeD.csv", 'w', encoding='utf-8') as hello:
                            hello.write(item+","+str(count))
                        print(item + "第" + str(count) + "页")
                        # endregion 记录当前节点及页码

                        register_page.wait_for_timeout(6000)  # 设置成 4 秒就不够稳定了，也许可以再等待长一点
                        register_page.wait_for_load_state('networkidle')
                        # time.sleep(5)
                        # btn = register_page.query_selector('button.btn-next')
                        flag = register_page.query_selector('button.btn-next').get_attribute('disabled')
                        count = count + 1
                        if flag is None:
                            register_page.click('button.btn-next')
                            # register_page.click('//*[@id="home"]/div[3]/div[3]/div/button[2]')
                            register_page.wait_for_load_state('networkidle')
                        else:
                            countStr = 1
                            break
            # time.sleep(2)
            page.wait_for_timeout(2000)
            browser.close()


def init():
    global storeList
    list = ['粤CB0', '粤CB1', '粤CB2', '粤CB6', '粤CB750', '粤CB751', '粤CB752', '粤CB753', '粤CB754',
            '粤CB755', '粤CB756', '粤CB757', '粤CB758', '粤CB759', '粤CB76', '粤CD', '川CA0', '川CA3', '川CA8', '川CB ',
            '川CB0', '川CB1', '川CB2', '川CB3', '川CB5', '川CB9', '川CB812', '川CB813', '川CB816', '川CB817', '川CB818',
            '川CB82', '川CB83', '川CB87']
    # '冀CA', '冀CB（', '冀CB(', '冀CB0', '冀CB1', '冀CB11', '冀CB13', '冀CB17', '冀CB2','滇CB', '辽CA',
    # '冀CB3', '冀CB5', '冀CB6', '冀CD','鲁CB532',
    #             '豫CB2', '豫CB32', '豫CB33', '豫CB34', '豫CB36', '豫CB371', '豫CB372', '豫CB370', '豫CB373', '豫CB34', '豫CB375',
    #             '豫CB376', '豫CB377', '豫CB38', '豫CB379', '豫CB39', '豫CB7', '豫CB9', '滇CA','辽CB0', '辽CB1',
    # '辽CB41', '辽CB42', '辽CB43', '黑CA', '黑CB', '湘CA73', '湘CA74', '湘CA74','湘CB', '皖CA', '皖CB-', '皖CB0', '皖CB1',
    #             '皖CB55', '皖CB56','鲁CA','鲁CB  ','鲁CB0','鲁CB1','鲁CB2','鲁CB3','鲁CB50','鲁CB51','鲁CB52','鲁CB530','鲁CB531',
    # '鲁CB533','鲁CB534',
    # '吉B', '苏B', '浙B', '冀B', '豫B', '滇B', '辽B', '黑B', '湘B', '皖B', '鲁B', '赣B', '鄂B', '甘B', '晋B', '陕B',
    #             '闽B', '黔B', '粤B', '川B', '青B', '藏B', '琼B', '新B', '桂B', '宁B', '蒙B', '藏B', '京B', '津B', '沪B',
    # '鲁CB535','鲁CB536','鲁CB537','鲁CB538','鲁CB539','鲁CB54','鲁CB59','鲁CD',
    #             '苏CA','粤CA','粤CB ',
    # '冀A'

    storeList = ['冀D', '冀 D',
                 '豫DA0', '豫DA1', '豫DA7', '豫DA31', '豫DA36', '豫DA37', '豫DA39', '豫DB',
                 '滇D',
                 '辽DA', '辽DB', '辽DC',
                 '黑DA', '黑DB', '黑DC', '黑DN',
                 '湘D', '湘 D', '湘Ｄ',
                 '皖DA', '皖DB',
                 '鲁DA', '鲁DB', '鲁DS', '鲁DX',
                 '苏DA ', '苏DA0', '苏DA1', '苏DA2', '苏DA51', '苏DA52', '苏DA57', '苏DB', '苏DS',
                 '浙DA', '浙DB',
                 '赣D',
                 '鄂D',
                 '甘D',
                 '晋Ｄ', '晋D',
                 '陕DA', '陕DB', '陕DC', '陕DD', '陕DE',
                 '吉DA', '吉DB', '吉DC', '吉DH', '吉DS',
                 '闽D',
                 '黔DA', '黔DB',
                 '粤DA', '粤DB0', '粤DB1', '粤DB2', '粤DB3', '粤DB6', '粤DB72', '粤DB750', '粤DB751', '粤DB752', '粤DB753',
                 '粤DB754', '粤DB755', '粤DB756', '粤DB757', '粤DB758', '粤DB759', '粤DB760', '粤DB762', '粤DB763', '粤DB766',
                 '粤DB768', '粤DB769',
                 '川D',
                 '青D',
                 '藏D',
                 '琼D',
                 '新D',
                 '桂D',
                 '宁D',
                 '蒙D',
                 '京D',
                 '津D',
                 '沪D',
                 '渝DA', '渝DB', '渝DC', '渝DD', '渝DS', '渝D工', 'end']


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # a= '共 9990 条'
    # print(a.split(' ',2)[1])
    init()
    run()
